<!--
  author: tangcheng_cd
  create by: 2018/6/11
  descr: 简单条件面板
-->
<template>
  <div class="v-simple-condition">
    <div v-if="data.conditions.length > 1"
         class="outer-connector-button-box">
      <el-button @click="toggleOuterConnector(data)" type="primary" class="outer-connector-button">
        {{data.connector === 'and' ? '且': '或'}}
      </el-button>
    </div>
    <div v-for="(item, index) in data.conditions" :key="index" class="vsc-row">
      <!--<div class="vsc-connector" v-if="index !== 0">-->
        <!--<el-button @click="toggleConnector(item)" type="primary" class="vsc-connector-btn">-->
          <!--{{connectorText(item)}}-->
        <!--</el-button>-->
      <!--</div>-->
      <div class="vsc-field">
        <!--
        左侧域下拉列表
      -->
        <el-select v-model="item.field1"
                   @change="emitInputValue"
                   class="pull-left" placeholder="请选择表1字段">
          <el-option
            v-for="option in options1"
            :key="option.meta_id"
            :label="option.colume_chs"
            :value="option.table_name +'.'+ option.colume_name	">
          </el-option>
        </el-select>
        <!--
          条件域连接按钮
        -->
        <div class="connector-button-box pull-left">
          <el-button class="connector-button" type="primary">
            等于
          </el-button>
        </div>
        <!--
          右侧域下拉列表
        -->
        <el-select v-model="item.field2"
                   @change="emitInputValue"
                   class="pull-left" placeholder="请选择表2字段">
          <el-option
            v-for="option in options2"
            :key="option.meta_id"
            :label="option.colume_chs"
            :value="option.table_name +'.'+ option.colume_name">
          </el-option>
        </el-select>
        <!--
          删除按钮：
            最少要保留一行不删除，所以只有一行不显示该按钮
        -->
        <div v-show="data.conditions.length > 1"
             class="vsc-btn vsc-remove-btn pull-left"
             @click="removeVSCRow(item, index)">
          <i class="iconfont icon-close"></i>
        </div>
        <!--
          新增按钮
        -->
        <div class="vsc-btn vsc-add-btn pull-left" @click="addVSCRow(index)">
          <i class="iconfont icon-add"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import ajax from '../../../../api/ajax/ajax'
import api from '../../../../api/url'

let defaultRow = {
  field1: null,
  oper: '=',
  field2: null
}

let connectors = ['and', 'or', '(', ')']
let connectorsText = {
  'and': '且',
  'or': '或',
  '(': '(',
  ')': ')'
}

export default {
  name: 'meta-tbl-column-simple-condition',
  data () {
    return {
      data: {
        connector: 'and',
        conditions: [
          defaultRow
        ]
      },
      // 域1下拉列表待选值
      options1: [],
      // 域2下拉列表待选值
      options2: []
    }
  },
  props: {
    // 值
    value: String,
    t1_meta_id: String,
    t2_meta_id: String
  },
  methods: {
    // 设置选择域1的可选值
    setOptions1Data (tableMetaId) {
      let postData = {
        meta_id: tableMetaId
      }
      ajax.post(api.SELECT_META_COLUME_BY_TABLEID, postData).then(res => {
        this.options1 = res.data
      })
    },
    // 设置选择域2的可选值
    setOptions2Data (tableMetaId) {
      let postData = {
        meta_id: tableMetaId
      }
      ajax.post(api.SELECT_META_COLUME_BY_TABLEID, postData).then(res => {
        this.options2 = res.data
      })
    },
    // 切换连接器(外层)
    toggleOuterConnector (item) {
      item.connector = (item.connector === 'and') ? 'or' : 'and'
      // 通知值改变
      this.emitInputValue()
    },
    // 切换连接器（内部）
    toggleConnector (item) {
      let index = connectors.indexOf(item.connector)
      let nextIndex = (index === connectors.length - 1) ? 0 : index + 1
      item.connector = connectors[nextIndex]
    },
    // 获取连接字符
    connectorText (item) {
      return connectorsText[item.connector]
    },
    // 新增一行
    addVSCRow (curIndex) {
      let newRow = JSON.parse(JSON.stringify(defaultRow))
      this.data.conditions.splice(curIndex + 1, 0, newRow)
      // 通知值改变
      this.emitInputValue()
    },
    // 移除一行
    removeVSCRow (item, index) {
      this.data.conditions.splice(index, 1)
      // 通知值改变
      this.emitInputValue()
    },
    // 解析value
    analyseValue () {
      if (this.value) {
        let result = {
          connector: 'and',
          conditions: []
        }
        // a.f1 = b.f1 and a.f2 = b.f2
        let arr1 = this.value.split(/\sand\s/)
        let connector = ''
        let andFlag = false
        let orFlag = false
        if (arr1.length > 1) {
          andFlag = true
        } else {
          arr1 = this.value.split(/\sor\s/)
          if (arr1.length > 1) {
            orFlag = true
          }
        }
        if (andFlag) {
          connector = 'and'
        } else if (orFlag) {
          connector = 'or'
        } else {
          // 如果出现了只有一条连接关系串的时候，外层默认连接符为and
          connector = 'and'
        }
        result.connector = connector
        arr1.forEach(item1 => {
          // Array [ "a.f1 = b.f1", "a.f2 = b.f2" ]
          let arr2 = item1.trim().split(/=/)
            result.conditions.push({
              field1: arr2[0].trim(),
              oper: '=',
              field2: arr2[1].trim()
            })
          // arr2.forEach(item2 => {
          //   // Array [ "a.f1", "b.f1" ]
          //   let arr3 = item2.trim().split(/\./)
          //   // Array [ "a", "f1" ]
          //   result.conditions.push({
          //     field1: arr3[0],
          //     oper: '=',
          //     field2: arr3[1]
          //   })
          // })
        })
        this.data = result
      } else {
        this.data = {
          connector: 'and',
            conditions: [
              defaultRow
            ]
        }
      }
    },
    // 编译值
    compileValue () {
      let result = ''
      for (let i = 0; i < this.data.conditions.length; i++) {
        let condtion = this.data.conditions[i]
        // 只有两个域都是有值才是可用值
        if (condtion.field1 !== null && condtion.field2 !== null) {
          result += `${condtion.field1} = ${condtion.field2}`
          if (i !== this.data.conditions.length - 1) {
            result += ` ${this.data.connector} `
          }
        }
      }
      return result
    },
    // emit input value 通知值改变
    emitInputValue () {
      let value = this.compileValue()
      // console.info('compileValue:')
      // console.info(value)
      this.$emit('input', value)
    }
  },
  created () {
    if (this.t1_meta_id) {
      this.setOptions1Data(this.t1_meta_id)
    }
    if (this.t2_meta_id) {
      this.setOptions2Data(this.t2_meta_id)
    }
    this.analyseValue()
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.v-simple-condition:before
  content ''
  width 0
  height calc(100% - 20px)
  border-left 1px solid #D8DCE5
  position absolute
  left 15px
  top 10px
.v-simple-condition
  padding-left 40px
  position relative
  .outer-connector-button-box
    position absolute
    left 0
    top 50%
    margin-top -15px
    .outer-connector-button
      width 30px
      height 30px
      padding 0
  .vsc-row
    .vsc-connector
      .vsc-connector-btn
        width 30px
        height 30px
        padding 0
    .vsc-field
      height 40px
      .el-select
        height 40px
        margin 0px
      .vsc-btn
        cursor pointer
        height 40px
        line-height 40px
        margin 0px 0px 0px 10px
      .connector-button-box
        height 40px
        line-height 40px
        margin 0px 10px
        .connector-button
          width 40px
          height 30px
          padding 5px
</style>
